package myJs

import myJs.myPkg.bootstrap.Bootstrap.default._
import myJs.Utils._
import myJs.Implicits._
import myJs.myPkg._
import myJs.myPkg.jquery._
import org.scalajs.dom.ext.Ajax
import org.scalajs.dom.{FormData, _}
import org.scalajs.dom.raw.HTMLFormElement
import scalatags.Text.all._

import scala.scalajs.js
import scala.scalajs.js.JSON
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import scala.scalajs.js.JSConverters._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.scalajs.js.Dynamic.{global=>g}

/**
 * Created by yz on 2019/4/25
 */
@JSExportTopLevel("MetaboDbDetail")
object MetaboDbDetail {


  @JSExport("init")
  def init = {
    initTable
    refreshTable(showLayer = true)
    refreshMetaboDbInfo

  }

  def initTable = {
    val tableId = "table"
    val columnNames = List("index", "name", "strandardName", "superclass", "accession", "keggid")
    val columnNameMap = Map(
      "index" -> "Index",
      "name" -> "Name",
      "strandardName" -> "Standard.name",
      "superclass" -> "Class",
      "keggid" -> "KeggID",
      "accession" -> "HMDBID",
      "keggId" -> "KeggID"
    )
    val columns = columnNames.map { columnName =>
      val title = columnNameMap.getOrElse(columnName, columnName)
      val fmt = tbFmt(columnName)
      ColumnOptions.field(columnName).title(title).sortable(true).formatter(fmt)
    }
    val options = TableOptions.columns(columns.toJSArray)
    $(s"#${tableId}").bootstrapTable(options)
  }

  def refreshMetaboDbInfo = {
    val url = g.jsRoutes.controllers.MetaboDbController.getMetaboDbById().url.toString
    Ajax.get(url = s"${url}?id=${getId}").map { xhr =>
      val dict = JSON.parse(xhr.responseText).toJDS
      dict.foreach { case (k, v) =>
        $(s"#metaboDb #${k}").text(v)
      }
      dict
    }
  }

  def getId = {
    g.id.toString
  }

  def refreshTable(f: () => js.Any = () => (), showLayer: Boolean = false) = {
    val index = if (showLayer) layer.alert(Tool.loadingElement, Tool.layerOptions) else 0
    val url = g.jsRoutes.controllers.MetaboDbController.getAllUserKeggInfo().url.toString
    val ajaxSettings = JQueryAjaxSettings.url(s"${url}?id=${getId}").contentType("application/json").
      `type`("get").success { (data, status, e) =>
      $("#table").bootstrapTable("load", data)
      layer.close(index)
      f()
    }
    $.ajax(ajaxSettings)

  }

  def tbFmt(columnName: String): js.Function = (v: js.Any) => columnName match {
    case _ => v
  }

}
